﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using FNSShoppingCart;
public partial class Pages_Store_ProductDetails : System.Web.UI.Page
{
    private StoreApplicationService sas = new StoreApplicationService();

    protected void Page_Load(object sender, EventArgs e)
    {
        //LinkButton1_Click(sender, e);
        Message_tb.TextMode = TextBoxMode.MultiLine;

        int productID;
        Int32.TryParse(Page.RouteData.Values["id"] as string, out productID);
        if (productID == 0)
        {
            Response.RedirectToRoutePermanent("Home");
            return;
        }
        if (!User.Identity.IsAuthenticated)
        {
            Subject_tb.Enabled = false;
            Message_tb.Enabled = false;
            Message_tb.Text = "Trebuie sa fi logat pentru a putea posta commenturi";
            Button1.Enabled = false;
        }
        var control = Page.LoadControl("~/Pages/WebControls/AlsoPurchased.ascx") as UserControl;
        AlsoPurchased.Controls.Add(control);
        Repeater5.DataBind();

        if (!Page.IsPostBack)
        {
            LinkButton1_Click(sender, e);
            sas.IncrementViewToProduct(productID);
        }
    }
    public string InStock(string stock)
    {
        if (Convert.ToInt32(stock) > 0)
        {
            return "<span class=\"blue\">In stoc</span>";
        }
        else
        {
            return "<span class=\"blue\">Nu e in stoc</span>";
        }
    }
    public string RezolveTheUrl(object url)
    {
        return Page.ResolveUrl(url as string);
    }

    public string disponibilitate_status(bool disponibilitate, int stoc_magazin, int stoc_producator)
    {
        if (disponibilitate == false)
            return "Nu este in stoc";

        if (stoc_magazin > 0)
            return "In stoc magazin";

        if (stoc_producator > 0)
            return "In stoc producator";

        return "Nu este in stoc";
    }

    public string show_old_price(string price)
    {
        if (Convert.ToDecimal(price) == 0)
            return "";

        return String.Format("{0:0,0.##}", Eval("old_price")) + " RON";
    }

    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        descriere_button_1.Attributes["class"] = "title_box_vizualizare_produs_selected";
        descriere_button_2.Attributes["class"] = "title_box_vizualizare_produs";
        Descriere_produs.Visible = true;
        Comentarii_produs.Visible = false;
    }
    protected void LinkButton2_Click(object sender, EventArgs e)
    {
        descriere_button_1.Attributes["class"] = "title_box_vizualizare_produs";
        descriere_button_2.Attributes["class"] = "title_box_vizualizare_produs_selected";
        Descriere_produs.Visible = false;
        Comentarii_produs.Visible = true;
    }

    #region "DBA"
    string GetConnectionString(string connection_name = "StoreDBConnectionString")
    {
        string connection = string.Empty;

        connection = ConfigurationManager.ConnectionStrings[connection_name].ConnectionString;

        return connection;
    }
    #endregion

    protected void Button1_Click(object sender, EventArgs e)
    {
        string Product_ID = Page.RouteData.Values["id"].ToString();
        var user = System.Web.Security.Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString();

        if (User.Identity.IsAuthenticated == false)
        {
            Response.RedirectToRoutePermanent("Login", new { ReturnUrl = "Produs/" + Product_ID });
            return;
        }

        try
        {
            SqlConnection connection = new SqlConnection(GetConnectionString());      //deschid conexiune catre baza de date
            SqlCommand command = new SqlCommand("Comments_Insert", connection);          //invoc procedura stocata
            command.CommandType = CommandType.StoredProcedure;                        //setez ca o sa chem o procedura stocata

            command.Parameters.AddWithValue("@Message", Message_tb.Text);
            command.Parameters.AddWithValue("@Title", Subject_tb.Text);
            command.Parameters.AddWithValue("@UserID", user);
            command.Parameters.AddWithValue("@ProductID", Product_ID);

            connection.Open();
            int nr_insert = command.ExecuteNonQuery();      //numarul de inserturi in baza de date
            connection.Close();

            if (nr_insert == 2)   //adica s-au facut 2 inserturi
            {
                //TODO mesaj de succes
            }
            else
            {
                //TODO mesaj de eroare
            }

            Repeater5.DataBind();
        }
        catch (Exception Exc)
        {
            //CAZ DE EROARE il trimit pe home
            Response.RedirectToRoutePermanent("Home");
        }
    }

    protected void Add_Rating(int rating_points)
    {
        string Product_ID = Page.RouteData.Values["id"].ToString();
        var userID = System.Web.Security.Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString();

        //procedura stocata ca sa imi inregistreze cererea :D
        try
        {
            SqlConnection connection = new SqlConnection(GetConnectionString());      //deschid conexiune catre baza de date
            SqlCommand command = new SqlCommand("Rating_Vote_User", connection);          //invoc procedura stocata
            command.CommandType = CommandType.StoredProcedure;                        //setez ca o sa chem o procedura stocata

            /*
              @UserID uniqueidentifier,
              @points int,
              @ProductID int,
              @Rating_aux_id int
            */

            command.Parameters.AddWithValue("@UserID", userID);
            command.Parameters.AddWithValue("@points", rating_points);
            command.Parameters.AddWithValue("@ProductID", Product_ID);
            command.Parameters.AddWithValue("@Rating_aux_id", 0);

            connection.Open();
            int nr_insert = command.ExecuteNonQuery();      //numarul de inserturi in baza de date
            connection.Close();

            Repeater4.DataBind();
        }
        catch (Exception Exc)
        {
            //fac ceva aici :D
        }
    }

    protected void Image_Url0(object sender, EventArgs e)
    {
        Add_Rating(1);
    }
    protected void Image_Url1(object sender, EventArgs e)
    {
        Add_Rating(2);
    }
    protected void Image_Url2(object sender, EventArgs e)
    {
        Add_Rating(3);
    }
    protected void Image_Url3(object sender, EventArgs e)
    {
        Add_Rating(4);
    }
    protected void Image_Url4(object sender, EventArgs e)
    {
        Add_Rating(5);
    }
    protected void LinkButton3_Click(object sender, EventArgs e)
    {
        int productID = Convert.ToInt32(Page.RouteData.Values["id"]);
        MyShoppingCart cart = new MyShoppingCart();
        String cartID = cart.GetShoppingCartId();
        cart.AddItem(cartID, productID, 1);
        Response.RedirectToRoutePermanent("ProductDetails",new{id = productID, prodName=Page.RouteData.Values["prodName"]});
    }
}